package com.gx.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.gx.common.exception.CommonException;
import com.gx.dal.dataobj.SysUserDo;
import com.gx.dal.mapper.SysUserMapper;
import com.gx.dto.command.LoginCmd;
import com.gx.service.AuthService;
import com.gx.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.SpringProperties;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Desc
 * @Author ZhaoYang Wang
 * @Create 2024/4/7 17:03
 * @Version 0.0.1
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private SysUserMapper userMapper;
    @Override
    public String login(LoginCmd loginCmd) {
        //从SpringProperties中获取应用名称
        String appName = SpringProperties.getProperty("spring.application.name");

        //用账号看看用户在不在 获取用户信息 判断传来的账号是否为空
        SysUserDo sysUserDo = userMapper.selectByAccount(loginCmd.getAccount());
        if(ObjectUtil.isNull(sysUserDo)){
            throw new CommonException("用户不存在");
        }
        //用户存在 解密 校验密码是否正确
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        //验证密码  如果密码正确
        if (bCryptPasswordEncoder.matches(loginCmd.getPassword(), sysUserDo.getPassword())) {
            //通过id登录
/*            StpUtil.login(sysUserDo.getId());
            //放到session里
            StpUtil.getSession().set("user", JSONObject.toJSONString(sysUserDo));*/

            return "";
        }
        //密码错误
        throw new CommonException("账号或密码错误");
    }
}
